package com.stylefeng.guns.rest.emailserver;


import com.stylefeng.guns.rest.pojo.EmailObject;
import org.slf4j.LoggerFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author yuzih
 * @create 2018-05-22 16:20
 * @desc 邮件发送工具类
 **/
public class MailController implements Runnable {
    private MailServer mailServer;
    private Session session;
    private EmailObject email;

    private MailController() {
    }

    public static MailController init(MailServer mailServer, EmailObject email) {
        MailController mailController = new MailController();
        mailController.mailServer = mailServer;
        mailController.email = email;
        mailController.session = Session.getDefaultInstance(mailServer.getProperties(), new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(email.getHostAddress(), email.getHostPassword()); //发件人邮件用户名、密码
            }
        });
        return mailController;
    }

    @Override
    public void run() {
        try {
            System.out.println("开始发送邮件！");
            LoggerFactory.getLogger(MailController.class).info(":Hello World!");
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(email.getHostAddress()));

            // Set Subject: 头部头字段
            message.setSubject(email.getTitle());

            // 设置消息体
            message.setText(email.getContent());

            Address[] targets = email.getAddressArr();

            // Set To: 头部头字段
            message.addRecipients(Message.RecipientType.TO, targets);

            // 发送消息
            Transport.send(message);

        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}
